package com.flywen.utils;

import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

public class SignUtils {
    public SignUtils() {
    }

    private static String mapJoin(Map<String, String> params) {
        if (!params.isEmpty()) {
            Map<String, Object> sortMap = new TreeMap();
            sortMap.putAll(params);
            StringBuffer sb = new StringBuffer();
            Iterator var4 = sortMap.keySet().iterator();

            String key;
            while(var4.hasNext()) {
                key = (String)var4.next();
                if (StringUtils.isNotBlank((CharSequence)params.get(key))) {
                    sb.append(key).append("=").append((String)params.get(key)).append("&");
                }
            }

            key = StringUtils.substringBeforeLast(sb.toString(), "&");
            return key.toString();
        } else {
            return "";
        }
    }

    public static String sign(Map<String, String> params, String key) {
        String str = mapJoin(params);
        str = str.concat("&").concat(key).concat("=").concat(key);
        String sign = DigestUtils.md5Hex(str).toLowerCase();
        return sign;
    }

    public static boolean verifySign(Map<String, String> params, String key) {
        String sign = (String)params.get("sign");
        AssertUtils.isTrue(StringUtils.isNotBlank(sign), "9989", "sign can not blank");
        params.remove("sign");
        String internalSign = sign(params, key);
        return StringUtils.equals(sign, internalSign);
    }
}
